//
//  ActivityDetailViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/6/21.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD

class ActivityDetailViewController: UIViewController, ActivityFooterViewDelegate, TimeLabelDelegate {

    @IBOutlet weak var cyclePictureView: CyclePictureView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var playerNum: UILabel!
    @IBOutlet weak var diamondNum: UILabel!
    @IBOutlet weak var goodsNum: UILabel!
    @IBOutlet weak var goodsPrice: UILabel!
    @IBOutlet weak var detailWeb: UIWebView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var applyNum: UILabel!
    @IBOutlet weak var DetailWebHeight: NSLayoutConstraint!
    @IBOutlet weak var buttomView: UIView!
    @IBOutlet weak var timeView: UIView!
    //@IBOutlet weak var countDownLable: TimeLabel!
    var timeLabel: TimeLabel!
    var str: String = ""
    var timer: NSTimer!//定义定时器
    //底部视图
    lazy var activityFooterView = {
        return NSBundle.mainBundle().loadNibNamed("ActivityFooterView", owner: nil, options: nil).last as! ActivityFooterView
    }()

    
    @IBAction func backBtnDown(sender: UIBarButtonItem) {
        self.navigationController?.popViewControllerAnimated(true)
    }
    
   
    var model: ActivityDetailModel? {
        didSet {

            self.applyNum.text = model?.applynum
            self.titleLabel.text = model?.title
            self.playerNum.text = model?.limitstr
            self.diamondNum.text = model?.integral
            self.goodsNum.text = model?.partnum
            self.goodsPrice.text = model?.price
            self.setupView()
            self.UpDataTime()
        }
    }
    
    var id: Int? {
        didSet {
            DataTool.loadActivityDetailData(self.id!, completionHandler: { (detailData) -> Void in
                guard let newDataes = detailData else {
                    return
                }
                self.model = newDataes

               
            })
        }
    }
    
    deinit {
        self.timer?.invalidate()
    }
    var fontSize: Int?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //字体大小
        let str = ApplicationDelegate.fontSize()
        self.fontSize  =  Int( (str as NSString).intValue)
        
     
        // 去掉webView滚动条 swift
        activityFooterView.frame.size.width = SCREEN_WIDTH
        buttomView.addSubview(activityFooterView)
         activityFooterView.delegate = self
        for subView in detailWeb.subviews
        {
            let v = subView 
            if v.isKindOfClass(UIScrollView.self) == true
            {
                (v as! UIScrollView).showsHorizontalScrollIndicator = false
                (v as! UIScrollView).showsVerticalScrollIndicator = false
                (v as! UIScrollView).bounces = false
                (v as! UIScrollView).scrollEnabled = false
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.timer?.fireDate = NSDate.distantPast()
        self.tabBarController?.tabBar.hidden = true
    }
    
    override func viewDidDisappear(animated: Bool) {
       // self.timer?.invalidate()
        SVProgressHUD.dismiss()
         self.timer?.fireDate = NSDate.distantFuture()
    }
   
    //MARK: UpDataTime
    func UpDataTime(){

        
        timeLabel = TimeLabel.init(frame: CGRectMake((SCREEN_WIDTH/4), 40, 150, 80), endTime: self.model!.endtime)
        timeLabel.delegate = self
        timeLabel.textAlignment =  NSTextAlignment.Center
        self.timeLabel.start()
        self.timeView.addSubview(timeLabel)
    }
    //MARK:TimeLabelDelegate
    func changeLabelText(){
       
        self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(self.changePos), userInfo: nil, repeats: true)

        let count =  self.model?.gblist.count
        if count > 0{
            for index in 0...count! - 1{
                self.str += (self.model?.gblist[index].name)!
                self.str += "   "
                self.str += (self.model?.gblist[index].phone)!
                self.str += "   "
            }
        }
        self.timeLabel.font = UIFont.systemFontOfSize(13)
       
        self.timeLabel.text = "活动已结束   \(self.str)"
    }
    //MARK:target
    func changePos(){
        let curPos = self.timeLabel.center
        print("\(self.timeLabel.center.x)")
        // 当curPos的x坐标已经超过了屏幕的宽度
        if curPos.x < -100 {
            let jianJu: CGFloat = self.timeLabel.frame.size.width / 2
            
            // 控制蝴蝶再次从屏幕左侧开始移动
            self.timeLabel.center = CGPoint(x: SCREEN_WIDTH + jianJu, y: 20)
        }
        else {
            // 通过修改iv的center属性来改变iv控件的位置
            self.timeLabel.center = CGPoint(x: curPos.x - 5, y: 40)
        }
        //其实蝴蝶的整个移动都是————靠iv.center来去设置的
    }
    
    //MARK:ActivityFooterViewDelegate
    func reportBtnSelected(){
        let sb = UIStoryboard(name: "NewsList", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("CommentViewController") as! CommentViewController
        vc.requestID = String(self.model!.id)
        vc.type = "活动"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func shareBtnSelected(sender: UIButton){

        let shareParames = NSMutableDictionary()
        let url = String(format: "%@activity/fenxiang/\(self.model!.id)",BaseUrl)
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.model?.title,
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(sender, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }

    }
    func buyBtnSelected(){
        
        let sb = UIStoryboard.init(name: "NewsList", bundle: nil)
        
        let vc = sb.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
        
        vc.urlStr = self.model!.taobaourl
        
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func applyBtnSelected(){
        if ApplicationDelegate.isLogin() {
            let sb = UIStoryboard.init(name: "MySelf", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("securityVerificationVC") as! securityVerificationVC
            vc.id = Int((self.model?.id)!)!
            vc.type = "活动"
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            let sb = UIStoryboard(name: "Login", bundle: nil)
            
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            
            self.navigationController?.pushViewController(vc, animated: true)

        }
    }
    
    func setupView() -> Void {
        var imageURLArray: [String] = []
        
        for pic in model!.activitypics {
            imageURLArray.append(pic.imgurl)
        }
        
        cyclePictureView.imageURLArray = imageURLArray
        cyclePictureView.autoScroll = true
        cyclePictureView.placeholderImage = UIImage(named: "placeholder")
        cyclePictureView.timeInterval = 2
        
        self.setupWebView()
    }
    
    func setupWebView() -> Void {
        self.detailWeb.delegate = self
        
        let css = NSBundle.mainBundle().URLForResource("Details.css", withExtension: nil)!
        
        var html = "<html>"
        
        html += "<head>"
        html += "<link rel=\"stylesheet\" href="
        html += "\"\(css)\""
        html += ">"
        html += "</head>"
        
        html += self.getBody()
        html += "</html>"
        
        self.detailWeb.loadHTMLString(html, baseURL: nil)
    }

    func getBody() -> String{

        var body = "<body>"
        body += "<h2 style='font-size:\(self.fontSize! + 5)px;'>活动介绍</h2>"
        body += model!.body
        body += "<body style='font-size: \(self.fontSize! + 2)px'>"
        for (index, detailImageModel) in self.model!.activityimgs.enumerate() {
            var imgTag = "<div class=\"image\">"
            
            imgTag += "<img id=\"\(index)\" "
            //用 * 符号切割字符串，"haha*hehe*xixi" ==>  "haha" "hehe" "xixi"
            let pixel = detailImageModel.pixel.componentsSeparatedByString("*")
            var width = (Float(pixel.first!) ?? 0)
            var height = (Float(pixel.last!) ?? 0)
            
            let maxWidth = Float(self.view.bounds.width * 0.95)
            if width > maxWidth {
                height =  height *  maxWidth / width
                width = maxWidth
            }
            
            // 这里是添加图片点击事件
            imgTag += "onload="
            imgTag += "\""
            imgTag += "this.onclick = function() {  window.location.href = 'sx:index=' +this.id;};"
            imgTag += "\""
            
            imgTag += "width=\(width) "
            imgTag += "height=\(height) "
            imgTag += "src=\(detailImageModel.src)>"
            
            imgTag += "<div class=\"imageDetail\">"
            imgTag += "\(detailImageModel.alt)"
            imgTag += "</div>"
            
            
            imgTag += "</div>"
            
            // 替换位置
            body = body.stringByReplacingOccurrencesOfString(detailImageModel.ref, withString: imgTag)
        }
        body += "<h2 style='font-size:\(self.fontSize! + 5)px;'>活动说明与流程</h2>"
        body += model!.introduce
        for (index, detailImageModel) in self.model!.activityimglcs.enumerate() {
            var imgTag = "<div class=\"image\">"
            
            imgTag += "<img id=\"\(index)\" "
            //用 * 符号切割字符串，"haha*hehe*xixi" ==>  "haha" "hehe" "xixi"
            let pixel = detailImageModel.pixel.componentsSeparatedByString("*")
            var width = Float(pixel.first!) ?? 0
            var height = Float(pixel.last!) ?? 0
            
            let maxWidth = Float(self.view.bounds.width * 0.95)
            if width > maxWidth {
                height =  height *  maxWidth / width
                width = maxWidth
            }
            
            // 这里是添加图片点击事件
            imgTag += "onload="
            imgTag += "\""
            imgTag += "this.onclick = function() {  window.location.href = 'sx:index=' +this.id;};"
            imgTag += "\""
            
            imgTag += "width=\(width) "
            imgTag += "height=\(height) "
            imgTag += "src=\(detailImageModel.src)>"
            
            imgTag += "<div class=\"imageDetail\">"
            imgTag += "\(detailImageModel.alt)"
            imgTag += "</div>"
            
            
            imgTag += "</div>"
            
            // 替换位置
            body = body.stringByReplacingOccurrencesOfString(detailImageModel.ref, withString: imgTag)
        }
        body += "</body>"
        
        return body
    }
}

extension ActivityDetailViewController: UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        self.detailWeb.frame.size.height = self.detailWeb.scrollView.contentSize.height
        self.scrollView.contentSize.height += self.detailWeb.scrollView.contentSize.height + 100
        
        DetailWebHeight.constant = self.detailWeb.scrollView.contentSize.height + 100
        self.detailWeb.layoutIfNeeded()
        //self.view.addConstraint(NSLayoutConstraint(item: detailWeb, attribute: .Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 0, constant: CGFloat(self.detailWeb.frame.size.height)))
        
        //self.view.addConstraint(NSLayoutConstraint(item: detailWeb, attribute: .Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 0, constant: CGFloat(self.detailWeb.frame.size.width)))
    }
    
}
